<template>
  <div class="container">
    <div class="app-container">
      <div class="role-operate">
        <el-button v-permission="'add-role'" type="primary" size="mini" @click="dialogVisible = true">添加角色</el-button>
      </div>
      <el-table :data="list">
        <!-- 角色列 -->
        <el-table-column align="center" prop="name" label="角色" width="200">
          <template slot-scope="scope">
            <el-input v-if="scope.row.isEdit" v-model="scope.row.newObj.name" size="mini" />
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>

        <!-- 启用状态列 -->
        <el-table-column align="center" label="启用" width="200">
          <template slot-scope="scope">
            <el-switch
              v-if="scope.row.isEdit"
              v-model="scope.row.newObj.state"
              :active-value="1"
              :inactive-value="0"
              size="mini"
            />
            <span v-else>{{ scope.row.state === 1 ? '已启用' : scope.row.state === 0 ? '未启用' : '' }}</span>
          </template>
        </el-table-column>

        <!-- 描述列 -->
        <el-table-column align="center" prop="description" label="描述">
          <template slot-scope="scope">
            <el-input
              v-if="scope.row.isEdit"
              v-model="scope.row.newObj.description"
              size="mini"
              type="textarea"
              :rows="3"
            />
            <span v-else>{{ scope.row.description }}</span>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <!-- 编辑状态列 -->
            <template v-if="scope.row.isEdit">
              <el-button type="primary" size="mini" @click="editRole(scope.row)">确定</el-button>
              <el-button size="mini" @click="CancelFn(scope.row)">取消</el-button>
            </template>
            <template v-else>
              <!-- 点击切换编辑 -->
              <el-button type="text" @click="handleAssignPermissions(scope.row)">分配权限</el-button>
              <el-button type="text" @click="handleEdit(scope.row.id)">编辑</el-button>
              <template>
                <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="handleDelete(scope.row)">
                  <el-button slot="reference" style="margin-left: 10px;" type="text">删除</el-button>
                </el-popconfirm>
              </template>
            </template>
          </template></el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-row type="flex" justify="end" style="height: 60px" align="middle">
        <el-pagination
          :current-page="page"
          layout="prev, pager, next"
          :total="total"
          :page-size="pagesize"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>

    <!-- 弹窗 -->
    <el-dialog title="分配权限" :visible.sync="dialogVisible" width="30%" @close="resetForm">
      <el-form ref="form" label-width="120px" :model="form" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="form.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" style="width:300px" size="mini" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button size="mini" type="primary" @click="onsubmit">确认</el-button>
              <el-button size="mini" @click="resetForm">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 放置权限弹层 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <!-- 放置权限数据 -->
      <el-tree
        ref="tree"
        :data="permissionData"
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="permIds"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getRoles, addRole, getRoleDetail, editRole, delRole, assignPerm } from '@/api/role'
import { getTree } from '@/utils'
import { getPermissionList } from '@/api/permission'

export default {
  name: 'Role',
  data() {
    return {
      list: [],
      total: null,
      page: 1,
      pagesize: 10,
      dialogVisible: false,
      form: {
        name: '',
        state: 1,
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      showPermissionDialog: false,
      permissionData: [],
      permIds: []
    }
  },
  created() {
    this.getRolesFn()
  },
  methods: {
    // 获取角色列表
    async getRolesFn() {
      const params = {
        page: this.page,
        pagesize: this.pagesize
      }
      const res = await getRoles(params)
      console.log(res)
      this.list = res.rows
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'newObj', { ...item })
      })
      // console.log(this.list)
      this.total = res.total
    },
    // 添加角色
    async onsubmit() {
      await this.$refs.form.validate()
      await addRole(this.form)
      this.resetForm()
      this.getRolesFn()
    },
    // 重置
    resetForm() {
      this.form = {
        name: '',
        state: 1,
        description: ''
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      this.dialogVisible = false
    },
    // 分页
    handleCurrentChange(page) {
      this.page = page
      // 重新获取数据
      this.getRolesFn()
    },
    // 分配权限
    async handleAssignPermissions(row) {
      this.currentRoleId = row.id
      // 获取角色已有权限
      const { permIds } = await getRoleDetail(row.id)
      this.permIds = permIds
      // 获取权限数据转为树状
      this.permissionData = getTree(await getPermissionList(), 0)
      this.showPermissionDialog = true
    },
    // 确定权限分配
    async btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    },
    // 编辑
    handleEdit(id) {
      // console.log('编辑:', row)
      const item = this.list.find(item => item.id === id)
      item.isEdit = true
    },
    // 获取角色详情
    async getDetialFn(row) {
      // 根据id获取角色详情
      const res = await getRoleDetail(row.id)
      // 重新赋值
      await Object.assign(row, { ...res, isEdit: false })
    },
    // 取消编辑
    CancelFn(row) {
      this.getDetialFn(row)
      // 关闭编辑状态
      row.isEdit = false
    },
    // 提交编辑
    async editRole(row) {
      // 提交编辑
      await editRole(row.newObj)
      this.getDetialFn(row)
      // console.log('编辑:', item.newObj)
    },
    // 删除
    async handleDelete(row) {
      console.log('删除:', row)
      await delRole(row.id)
      // console.log(this.page, this.list.length)
      if (this.page > 1 && this.list.length === 1) {
        this.page--
      }
      this.getRolesFn()
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  .role-operate {
    padding: 10px;
  }
}
</style>
